/* 
 * Copyright 2011 VelocitiSoftware
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.velociti.ikarus.ui.widget;

import java.util.Map;

import com.vaadin.event.MouseEvents.ClickEvent;
import com.vaadin.event.MouseEvents.ClickListener;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.terminal.Resource;
import com.vaadin.terminal.gwt.client.MouseEventDetails;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.ClientWidget;
import com.velociti.ikarus.widget.client.ui.VIkarusDockItem;
/**
 * ######IkarusDockItem##### 
 * -Item used in IkarusDock
 * @author Alper Turkyilmaz - VelocitiSoftware - 2011
 * @version 1.0.2
 * 
 */
@ClientWidget(VIkarusDockItem.class)
public class IkarusDockItem extends AbstractComponent {
	private static final String CLICK_EVENT = VIkarusDockItem.CLICK_EVENT_IDENTIFIER;

	private Resource source = null;
	private String title;

	public IkarusDockItem(String title, Resource source) {
		setTitle(title);
		setSource(source);
	}

	public String getTitle() {
		return title;
	}

	public void setSource(Resource source) {
		if (source != null && !source.equals(this.source)) {
			this.source = source;
			requestRepaint();
		}
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Resource getSource() {
		return source;
	}

	public void paintContent(PaintTarget target) throws PaintException {
		target.addAttribute("type", "image");
		target.addAttribute("src", getSource());
		if (title != null) {
			target.addAttribute("title", title);
		}
	}

	public void addListener(ClickListener listener) {
		addListener(CLICK_EVENT, ClickEvent.class, listener, ClickListener.clickMethod);
	}

	public void removeListener(ClickListener listener) {
		removeListener(CLICK_EVENT, ClickEvent.class, listener);
	}

	public void changeVariables(Object source, Map<String, Object> variables) {
		super.changeVariables(source, variables);
		if (variables.containsKey(CLICK_EVENT)) {
			fireClick((Map<String, Object>) variables.get(CLICK_EVENT));
		}
	}

	private void fireClick(Map<String, Object> parameters) {
		MouseEventDetails mouseDetails = MouseEventDetails.deSerialize((String) parameters.get("mouseDetails"));
		fireEvent(new ClickEvent(this, mouseDetails));
	}
}
